package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一步交互由三部分构成
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 */

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //.1解析请求
            HttpRequest httpRequest=new HttpRequest(socket);

            //:2处理请求
            String patch=httpRequest.getUri();

            File file=new File("./webapps"+ patch);
            int statusCode=200;
            String statusReason="OK";
            if(file.exists()&&file.isFile() ){
                //正确情况
            }else {
                statusCode=404;
                statusReason="NotFound";
                file =new File("./webapps/root/404.html");
            }
            //:3发送响应
            OutputStream out=socket.getOutputStream();
            /*响应的大致内容:
            HTTP/1.1 200 OK(CRLF)
            Content-Type: text/html(CRLF)
            Content-Length: 2546(CRLF)(CRLF)
                    1011101010101010101......
*/
            String line=" HTTP/1.1"+" "+statusCode+" "+statusReason;
            byte[] data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//回车
            out.write(10);//换行
            //3.2发送响应头
            line="Content-Type: text/html";
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            line="Content-Length: "+file.length();
            data=line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            out.write(13);//提示发送完毕
            out.write(10);
            //3.3
            byte[] c=new byte[1024*10];
            FileInputStream fi=new FileInputStream(file);
            int len;
            while ((len=fi.read(c))!=-1) {
                out.write(c,0,len);
            }
            System.out.println("响应完毕");
            /*
                上述内容写好后，打开浏览器输入网址:http://localhost:8888/index.html
                测试读取浏览器发送过来的请求内容并在控制台上确认内容
             */
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //一次http交互后要与客户端断开链接（HTTP协议要求）
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
